const { mysql } = require('./qcloud')
const Koa = require('koa'),
  route = require('koa-route'),
  websockify = require('koa-websocket');

const app = websockify(new Koa());

const response = require('./middlewares/response')
const debug = require('debug')('koa-weapp-demo')
const bodyParser = require('koa-bodyparser')
const config = require('./config')


const jwt = require('koa-jwt')
const jsonwebtoken = require('jsonwebtoken')
const myws = require('./mywebsocket')
// 使用响应处理中间件
app.use(response)

// 解析请求体
app.use(bodyParser())


// 引入路由分发
const router = require('./routes')
app.use(router.routes())

//app.use(jwt({secret:'jwt dome'}))

var data = jsonwebtoken.verify(
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcm9tVXNlcklkIjoyNiwidG9Vc2VySWQiOiIyOSIsImlhdCI6MTUyNDY0Njc5OH0.ODvjZJ_XBMzH3RZuN25_wH8HRh2yMJTp1TqYohKJI1w", 'jwt dome')
console.log(data)
app.ws.use(function (ctx, next) {
  // return `next` to pass the context (ctx) on to the next ws middleware
  return next(ctx);
});

app.ws.use(route.all('/chat', function (ctx) {

  myws.addClient(ctx)

  //接收到消息
  //console.log(ctx.websocket.upgradeReq.url)
  ctx.websocket.on('message', function (msg) {
    myws.send(msg)

  });

  ctx.websocket.on('close', function () {
    myws.exit(ctx)


  });
}));


// 启动程序，监听端口
app.listen(config.port, () => debug(`listening on port ${config.port}`))
